
async function delay(t){
  return new Promise((resolve)=>{
    setTimeout(resolve,t);
  })
}


export default {

  namespace: 'example',

  state: {
    val1:'test',
    remoteOptions:[],
    rVal:[],
    fetching:false,
    fetchId:0,
    inputVal:'',
    remoteCheck:{
      checkVal:null,
      checkRes:true,
      loading:false
    },
    emValue:'244223',
    emOptions:[
      {
        id:'322432',
        name:'fdew'
      },{
        id:'82731',
        name:'test'
      }
    ]
  },

  subscriptions: {
    setup({ dispatch, history }) {
    },
  },

  effects: {
    *fetchRemote({ payload }, { call, put }) {

    },
    getData:[function*({ payload }, { call, put, select }){
      console.log('send')
      const {val} = payload;
      let fetchId = yield select(({example})=>example.fetchId);
      let newId = fetchId+1;
      yield put({type:'fetch',payload:{fetching:true,remoteOptions:[], fetchId:newId}});
      yield call(delay,parseInt(1000*Math.random()));
      fetchId = yield select(({example})=>example.fetchId);
      if(fetchId==newId){
        yield put({type:'fetch',payload:{
          fetching:false,
          remoteOptions:[
            val+'eddadadf',
            val+'degrtggdfv',
            val+'rggsufshf'
          ]
        }})
      } 
    },{ type: 'throttle', ms: 800 }],
    *remoteCheck({ payload }, { call, put, select }){
      yield put({type:'updateRemoteCheck',payload:{
        loading:true,
        checkVal:payload.value
      }});
      yield call(delay,2000);
      yield put({type:'updateRemoteCheck',payload:{
        loading:false,
        checkRes: Math.random()>0.5
      }});
    }
  },

  reducers: {
    fetch(state, action) {
      return { ...state, ...action.payload };
    },
    updateRemoteCheck(state, action){
      return {
        ...state,
        remoteCheck:{
          ...state.remoteCheck,
          ...action.payload
        }
      }
    }
  },

}

function delay(t){
  return new Promise(function(resolve,reject){
    setTimeout(function() {
      resolve()
    }, t);
  })
}


